import { cloneDeep, isEmpty, forEach, remove } from 'lodash';
import { DEFAULT_MENU } from './menus';
import { fetchMenus } from '../services/routerService';
import { getPermisstion } from 'enoad-component-web/dist/src/core/util';

const Model = {
  namespace: 'enoadRouter', // 命名空间
  state: {
    menus: [],
  }, // store 数据
  effects: {
    // 副作用 *的是异步方法
    *fetchMenus(_, { call, put }) {
      const res = yield call(fetchMenus, {});
      let menus = cloneDeep(DEFAULT_MENU);
      if (res.code === 200) {
        //获取成功。
        forEach(menus, (item) => {
          if (item.path === '/list' || item.path === '/track') {
            //如果是列表。
            forEach(res.data, (menu) => {
              if (getPermisstion(`${menu.apiKey}_select`)) {
                item.children.push({
                  path: menu.apiKey,
                  name: menu.name,
                });
              }
            });
          }
        });
        if (!getPermisstion('SystemTask_select')) {
          menus = remove(menus, (item) => {
            return item.path !== '/swing';
          });
        }
        if (!getPermisstion('XLSX_select')) {
          menus = remove(menus, (item) => {
            return item.path !== '/xlsx';
          });
        }
      }
      yield put({
        type: 'changeStatus',
        payload: { menus },
      });
    },
  },

  reducers: {
    // effect获取数据处理方法
    changeStatus(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
export default Model;
